package cn.itsource.aop;


import cn.itsource.domain.Log;

import cn.itsource.mapper.LogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Aspect
@Component
public class LogManager {
    @Autowired
    private LogMapper logMapper;
    @Around("@annotation(cn.itsource.annotation.Logs)")
    public Object addlog(ProceedingJoinPoint joinPoint) throws Throwable {
        Log log = new Log();
        log.setId(1L);
        log.setOperId(1L);
        //操作时间
        log.setOperTime(new Date());
        //获取-设置类名
        log.setClassName(joinPoint.getSignature().getDeclaringTypeName());
        //设置-获取方法名
        log.setMethodName(joinPoint.getSignature().getName());
        //设置方法返回值
//        log.setReturnValue(proceed.toString());
        //获取-设置ip
        // 获取当前的ServletRequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            HttpServletRequest request = servletRequestAttributes.getRequest();
            // 获取IP地址
            String ip = request.getRemoteAddr();
            // 将IP设置到Log对象
            log.setIp(ip);
        }
        //执行目标方法
        Object proceed = joinPoint.proceed();
        System.out.println("===========================================");
        System.out.println(log);
        System.out.println("===========================================");
        //保存
        logMapper.add(log);

        return proceed;
    }
}